import { IContextDescriptionItem } from '@/apis/chat/interfaces'
import { API_BASE_URL } from '@/utils/url'
import { ElMessage } from 'element-plus'

const charURLMap = {
    case: `${API_BASE_URL}/chat`,
    writing: `${API_BASE_URL}/writing-chat`,
    questionGen: `${API_BASE_URL}/question-gen-chat`,
    questionPointGen: `${API_BASE_URL}/question-point-gen-chat`,
}

export type IChatAgent = keyof typeof charURLMap

export interface IChatMessage {
    role: 'user' | 'assistant'
    content: string
}

export interface IChatApiData {
    user: string
    context?: IContextDescriptionItem[]
    knowledgeBase?: {
        id: number
        title: string
        collectionName: string
    }
    enableKnowledgeBase?: boolean
    messages?: IChatMessage[]
}

export const chat = async (
    data: IChatApiData,
    onData: (str: string) => any,
    chatType: IChatAgent = 'case',
    onComplete?: () => any
) => {
    const url = charURLMap[chatType]

    const resp = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            user: data.user,
            context: data.context,
            knowledgeBase: data.knowledgeBase,
            enableKnowledgeBase: data.enableKnowledgeBase,
            messages: data.messages || [],
        }),
    }).then((resp) => {
        if (!resp.ok) {
            ElMessage.error('请求失败')
            onData('请求失败')
            onComplete && onComplete()
            return
        }
        return resp
    })

    if (!resp) return

    const reader = resp.body?.getReader()

    while (true) {
        const { done, value } = (await reader?.read()) as {
            done: boolean
            value: Uint8Array
        }
        if (done) {
            onComplete && onComplete()
            break
        }
        const str = new TextDecoder().decode(value)

        // 正则匹配 data: {"text": "我"}\n\n
        const reg = /data: (.*)\n\n/g
        const match = reg.exec(str)
        if (match) {
            const data = JSON.parse(match[1])
            onData(data.text)
        }
    }

    return
}

// sseTest()
